<?php

namespace app\admin\controller\health\goods;

use app\common\controller\Backend;
use app\health\model\HealthGoodsAccess;

class GoodsAccess extends Backend
{

    public function index()
    {
        if ($this->request->isAjax()) {
            [$where, $sort, $order, $offset, $limit] = $this->buildparams();
            $params = $this->request->param();
            $data   = ['rows' => [], 'total' => 0];
            $where  = [];
            if (!empty($params['created_at']) && is_array($params['created_at']) && count($params['created_at']) === 2) {
                $where['created_at'] = ['between time', [$params['created_at'][0] . ' 00:00:00', $params['created_at'][1] . ' 23:59:59']];
            }
            $paginate = HealthGoodsAccess::where($where)
                ->with(['goods'])
                ->field('count(id) as total_num,goods_id,GROUP_CONCAT(user_id) as user_ids')
                ->group('goods_id')
                ->order('total_num', 'desc')
                ->paginate($limit);
            $lists    = [];
            foreach ($paginate->items() as $item) {
                $lists[] = [
                    'goods_id'   => $item->goods_id,
                    'goods_name' => $item->goods->goods_name,
                    'total_num'  => $item->total_num,
                    'total_user' => count(array_unique(explode(',', $item->user_ids)))
                ];
            }
            $data['rows']  = $lists;
            $data['total'] = $paginate->total();
            $this->success('查看用户', null, $data);
        }
        return $this->view->fetch();
    }
}